/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package CONTROLLER;

import COMMON.CauHoi;
import COMMON.NganHangCauHoi;
import MODEL.DAO.CustomizeQuizsDao;
import MODEL.DAO.ParametersDao;
import MODEL.DAO.TestResultsDao;
import MODEL.DAO.WarehousesDao;
import MODEL.POJO.Customizequizs;
import MODEL.POJO.Parameters;
import MODEL.POJO.Testresults;
import MODEL.POJO.Users;
import MODEL.POJO.Warehouses;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Tri ben tre
 */
@WebServlet(name = "BeginTestController", urlPatterns = {"/BeginTestController"})
public class BeginTestController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        //PrintWriter out = response.getWriter();
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");
        HttpSession session = request.getSession();
        ArrayList dsch = new ArrayList();
        try {
            Users u = (Users) session.getAttribute("user");
            if (u != null) {
                String action = (String) request.getParameter("action");
                if (action != null) {
                    if (action.equals("begin")) {
                        if (session.getAttribute("examCode") == null) {
                            int level = Integer.parseInt(request.getParameter("level"));

                            int idMaxOfUser = TestResultsDao.getMaxIDofUser(level, u.getUserIdentityCard());
                            int idMaxOfWarehouse = WarehousesDao.getMaxNumber(level);
                            Customizequizs cq = CustomizeQuizsDao.getLevel(level);
                            long timer = cq.getCustomizeQuizDeadline() * 60;
                            int numberQuestionEasy = cq.getCustomizeQuizQualityEasy();
                            int numberQuestionMedium = cq.getCustomizeQuizQualityMedium();
                            int numberQuestionHard = cq.getCustomizeQuizQualityHard();
                            int sumQuestion = numberQuestionHard + numberQuestionMedium + numberQuestionEasy;

                            int examCode = 0;
                            Warehouses wh = new Warehouses();
                            String path = request.getServletContext().getRealPath("\\");
                            if (NganHangCauHoi.getFlag() == 0) {
                                dsch = NganHangCauHoi.docDanhSachCauHoi(path);
                            }
                           
                            if (idMaxOfUser < idMaxOfWarehouse) // Lấy lại đề cũ
                            {
                                wh = WarehousesDao.getIDExamFromLevel(level, idMaxOfUser + 1);
                                String mergeQuestion = wh.getWarehouseEasy() + "," + wh.getWarehouseMedium() + "," + wh.getWarehouseHard();
                                dsch = new ArrayList();
                                dsch = NganHangCauHoi.getQuestionFromWarehouse(mergeQuestion);
                                dsch = NganHangCauHoi.randomQuestion(0, sumQuestion, sumQuestion, dsch);
                                examCode = wh.getWarehouseId();
                                session.setAttribute("examCode", examCode);
                            } else { // Random đề mới

                                ArrayList arrAllQuestionEasy = new ArrayList(NganHangCauHoi.getListQuestionEasy());
                                ArrayList arrQuestionEasy = NganHangCauHoi.randomQuestion(0, numberQuestionEasy, arrAllQuestionEasy.size(), arrAllQuestionEasy);

                                ArrayList arrAllQuestioMedium = new ArrayList(NganHangCauHoi.getListQuestionNormal());
                                ArrayList arrQuestioMedium = NganHangCauHoi.randomQuestion(0, numberQuestionMedium, arrAllQuestioMedium.size(), arrAllQuestioMedium);

                                ArrayList arrAllQuestionHard = new ArrayList(NganHangCauHoi.getListQuestionHard());
                                ArrayList arrQuestionHard = NganHangCauHoi.randomQuestion(0, numberQuestionHard, arrAllQuestionHard.size(), arrAllQuestionHard);

                                dsch = new ArrayList();
                                dsch.addAll(arrQuestionEasy);
                                dsch.addAll(arrQuestioMedium);
                                dsch.addAll(arrQuestionHard);


                                wh.setCustomizequizs(cq);
                                wh.setWarehouseEasy(NganHangCauHoi.SplitQuestions(arrQuestionEasy));
                                wh.setWarehouseMedium(NganHangCauHoi.SplitQuestions(arrQuestioMedium));
                                wh.setWarehouseHard(NganHangCauHoi.SplitQuestions(arrQuestionHard));
                                wh.setWarehouseNumber(idMaxOfWarehouse + 1);
                                boolean kq = WarehousesDao.addWarehouse(wh);

                                dsch = NganHangCauHoi.randomQuestion(0, sumQuestion, sumQuestion, dsch);
                                examCode = WarehousesDao.getLast_insert_id();

                            }
                            // Lưu lại thứ tự câu hỏi sau khi random
                            String str = "";
                            for (int i = 1; i <= dsch.size(); i++) {
                                CauHoi ch = (CauHoi) dsch.get(i - 1);
                                str = str + ch.getIdcauhoi();
                                if (i != dsch.size()) {
                                    str = str + ",";
                                }
                            }
                            Testresults testResult = new Testresults();
                            testResult.setTestResultDateTimeEnded(null);
                            testResult.setTestResultDateTimeStarted(new java.sql.Date(new java.util.Date().getTime()));
                            testResult.setTestResultScore((float) -1.00);
                            testResult.setUsers(u);
                            testResult.setWarehouses(wh);
                            testResult.setTestResultNumberOrder(str);
                            testResult.setTestResultAnswers("0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0");
                            boolean kq = TestResultsDao.addResult(testResult);
                            
                            Parameters paramCheck = ParametersDao.getParameters();
                            request.setAttribute("allCheck", paramCheck.getParametersCheck());
                            session.setAttribute("checked",null);
                            session.removeAttribute("checked");
                            request.setAttribute("timer", timer);
                            request.setAttribute("examCode", examCode);
                            request.setAttribute("testing", "1");
                            request.setAttribute("dsch", dsch);
                            session.setAttribute("idResult", TestResultsDao.getLast_insert_id());
                            session.setAttribute("examCode", examCode);
                            session.setAttribute("checked",null);
                            session.removeAttribute("checked");
                            request.getRequestDispatcher("User/StartTest.jsp").forward(request, response);

                        } else {
                            //if (session.getAttribute("testing") != null)
                            {
                                int idResult = Integer.parseInt(session.getAttribute("idResult").toString());
                                Testresults tr = TestResultsDao.GetResultByCode(idResult);
                                long deadline = tr.getWarehouses().getCustomizequizs().getCustomizeQuizDeadline();
                                Date date = tr.getTestResultDateTimeStarted();
                                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                                Date now = new Date();
                                Calendar cal = Calendar.getInstance();
                                //Date now = new java.sql.Date(new java.util.Date().getTime());
                                long remain = (deadline * 60) - ((now.getTime() - date.getTime()) / 1000);
                                String mergeQuestion = tr.getTestResultNumberOrder();
                                dsch = new ArrayList();
                                dsch = NganHangCauHoi.getQuestionFromWarehouse(mergeQuestion);
                                Parameters paramCheck = ParametersDao.getParameters();
                                request.setAttribute("allCheck", paramCheck.getParametersCheck());
                                request.setAttribute("timer", remain);
                                request.setAttribute("testing", "1");
                                request.setAttribute("dsch", dsch);
                                request.setAttribute("examCode", tr.getWarehouses().getWarehouseId());
                                request.getRequestDispatcher("User/StartTest.jsp").forward(request, response);
                            }
                        }
                    }
                }
            }
        } finally {
            //out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
